/* eslint-disable react-hooks/exhaustive-deps */
// 倒计时
// 输入，second秒数,callback执行回调
// 输出，count剩余秒数
import {useState,useEffect} from 'react'
 
export function useCutdown(second,callback){
  // 剩余秒数据
  const [count,setCount] = useState(second);
  /*
  // 清除定时器的id
  let clearId = null; //停止id
  // 什么时候开始倒计时，组件挂载完毕 
  useEffect(()=>{
    if(count==0){//如果等于0就返回不再执行
      callback?callback():''; //如果有callback执行callback
      return;
    }
    clearId = setTimeout(()=>{
      setCount(count-1)
    },1000)  //延迟1秒count减1
    // 组件下载移除定时器
    return ()=>{clearTimeout(clearId)}
  },[count]) //只要count变化都执行
  */
 const start = ()=>{
  setCount(second)
  setTimeout(()=>setCount(count-1),1000)
  
 }
 const reset = ()=>{

 }

 useEffect(()=>{
  if(count==second){return}
  if(count<=0){
    callback?callback():'';
    setCount(second);
    return
  }
   setTimeout(()=>setCount(count-1),1000)
 },[count])
  return [count,start,reset] 
}

 